/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DownloadSourcePrintFilesApplet.java
 *
 * Created on 2010-3-18, 10:20:21
 */

package ext.generic.doc;

import java.io.*;
import java.util.*;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JOptionPane;

import wt.security.FileAccess;
import wt.security.NetAccess;
import wt.security.RuntimeAccess;
import wt.security.WTJFileChooser;
import wt.util.WTContext;
import wt.fc.*;
import wt.doc.*;
import wt.access.*;

/**
 *用于客户端现在原始打印文件(没有经过电子签名打印的文件)
 * @author Administrator
 */
public class DownloadSourcePrintFilesApplet extends javax.swing.JApplet
{
    public static boolean VERBOSE=true;
    public static String signInfoFileName="filesSignInfo.txt";
    /** Initializes the applet DownloadSourcePrintFilesApplet */
    public void init() {
        if(VERBOSE)
        System.out.println(">>> init().");
       WTContext.init(this);
       if(VERBOSE)
        System.out.println("WTContext init.");
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
       if(VERBOSE)
        System.out.println("<<< init().");
    }

  /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        textField1 = new java.awt.TextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        textArea1 = new java.awt.TextArea();
        label1 = new java.awt.Label();

        jButton1.setText("浏览");
        jButton1.setActionCommand("browseDirectory");
        jButton1.setName("fileBrowserBtn"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        jButton2.setText("确定");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });

        textArea1.setEditable(false);
        textArea1.setName("downloadInfo"); // NOI18N

        label1.setName("downloadInfoLabel"); // NOI18N
        label1.setText("下载状态信息:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 309, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, 0, 0, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1))
                    .addComponent(textArea1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE))
                .addGap(12, 12, 12))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(jButton2))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGap(6, 6, 6)
                .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(textArea1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jButton1MouseClicked
    {//GEN-HEADEREND:event_jButton1MouseClicked
        // TODO add your handling code here:
        if(VERBOSE)
            System.out.println("    enter jButton1MouseClicked>>>>");
        FileAccess fa = FileAccess.getFileAccess();
        /*
        javax.swing.JFileChooser jFileChooser2 = new javax.swing.JFileChooser();
        jFileChooser2.setDialogTitle("选择下载目录");
        jFileChooser2.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);
        jFileChooser2.setName("filesDirectoryChooser"); // NOI18N
        jFileChooser2.showDialog(evt.getComponent(), "确定");
        textField1.setText(jFileChooser2.getSelectedFile().getAbsolutePath());
        */
        if(VERBOSE)
            System.out.println("    user WTJFileChooser..");
        wt.security.WTJFileChooser jfc = new wt.security.WTJFileChooser();
        jfc.setDialogTitle("选择下载目录");
        jfc.setName("filesDirectoryChooser");
        jfc.setFileSelectionMode(WTJFileChooser.DIRECTORIES_ONLY);
        jfc.showDialog(evt.getComponent(), "确认");
        textField1.setText(jfc.getSelectedFile().getAbsolutePath());
        if(VERBOSE)
            System.out.println("    quit jButton1MouseClicked");
    }//GEN-LAST:event_jButton1MouseClicked

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jButton2MouseClicked
    {//GEN-HEADEREND:event_jButton2MouseClicked
        // TODO add your handling code here:
          if(VERBOSE)
            System.out.println("    >>> button1MouseClicked");
          jButton2.setEnabled(false);
        try
        {
            String user = "[Authorization]";
            String auth = getParameter("authorization");
            String oids= getParameter("oids");
            if(VERBOSE)
            {
                System.out.println(" authorization=" + auth);
                System.out.println(" oids=" + oids);
            }
            FileAccess fa = FileAccess.getFileAccess();
            downloadFiles(fa, auth, oids);
        }
        catch(Exception ioe)
        {
            ioe.printStackTrace();
        }
        if(VERBOSE)
            System.out.println("    <<<quit button1MouseClicked");
    }//GEN-LAST:event_jButton2MouseClicked

/**
 *下载用户在Windchill中所选的文件
 * @param fa
 * @param auth 用户验证
 * @param oids 用户所选对象的oid
 * @throws java.lang.Exception
 */
    private void downloadFiles(FileAccess fa, String auth, String oids) throws Exception 
    {
        if(oids!=null)
        {
            HashMap downloadInfo= GenericDocCommands.getDownloadSourcePrintFilesInfo(oids);
            //构造流程签名信息文件
            File signInfoFile= getDestFile(fa, signInfoFileName);
            if(fa.exists(signInfoFile))
                fa.delete(signInfoFile);
            FileOutputStream fos = fa.getFileOutputStream(signInfoFile);

            PrintWriter pw= new PrintWriter(fos);
            //打印表头
            pw.println("#Number" + GenericDocCommands.info_sub_separator + "FileName" +  GenericDocCommands.info_sub_separator + "SignInfo");

            //下载文件
            int index=1;
            Iterator keys= downloadInfo.keySet().iterator();
            while(keys.hasNext())
            {
                String cadNumber= keys.next().toString();
                HashMap fileInfo=  (HashMap)downloadInfo.get(cadNumber);
                if(VERBOSE)
                {
                    System.out.println("    cadNumber="+ cadNumber);
                }
                HashMap fileSignInfo= (HashMap)fileInfo.get("fileSignInfo");

                Iterator keys1= fileSignInfo.keySet().iterator();
                while(keys1.hasNext())
                {
                    Object key= keys1.next();
                    String info= fileSignInfo.get(key).toString();
                    String infoItems[]= info.split(GenericDocCommands.info_sub_separator);
                    String fileName= infoItems[0];
                    String downloadUrl= infoItems[1];
                    String signInfo=  infoItems[2];
                    if(VERBOSE)
                    {
                        System.out.println("    cadNumber="+ cadNumber);
                        System.out.println("    fileName=" + fileName);
                        System.out.println("    downloadUrl=" + downloadUrl);
                        System.out.println("    signInfo=" + signInfo);
                    }
                    File dest= getDestFile(fa, fileName);
                    int result= checkDestFile(fa, dest);
                    if(result==1)
                    {
                        if(VERBOSE)
                            System.out.println("    目标文件已存在,且不容许覆盖,无需下载.");
                        continue;
                    }
                    else if(result==2)
                    {
                        if(VERBOSE)
                            System.out.println("    目标文件无法覆盖,出现错误..");
                        break;
                    }
                    downloadFile(fa, downloadUrl, auth, dest);
                    //打印签审信息内容
                    pw.println(cadNumber + GenericDocCommands.info_sub_separator  + fileName +  GenericDocCommands.info_sub_separator + signInfo);
                    String downloadStatusInfo= index + ",文件 " +fileName + " 已下载完成.\n";
                    textArea1.setText(textArea1.getText() + downloadStatusInfo);
                    index++;
                }
            }
            String downloadStatusInfo= "--------下载全部完成.---------\n";
            textArea1.setText(textArea1.getText() + downloadStatusInfo);
            pw.flush();
            fos.close();
        }
    }

/**
 * 下载文件
 * @param fa 客户端文件访问认证
 * @param fileurl
 * @param auth
 * @param file
 * @throws java.lang.Exception
 */
    private void downloadFile(FileAccess fa, String fileUrl,String auth, File dest) throws Exception
    {
        URL url = new URL(fileUrl);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.addRequestProperty("AUTHORIZATION", auth);
        NetAccess.getNetAccess().connect(uc);

        FileOutputStream fos = fa.getFileOutputStream(dest);
        InputStream is = uc.getInputStream();
        byte[] buf = new byte[4096];
        int len;
        try
        {
            while ((len = is.read(buf)) >= 0)
                fos.write(buf, 0, len);
        }
        finally
        {
            fos.close();
            is.close();
        }
    }

     /**
   *由原文件和下载目录构造目标文件
   * @param fa 文件处理授权
   * @param sourceFileName 原文件名
   * @return 目标文件
   */
    private File getDestFile(FileAccess fa, String sourceFileName)
    {
            String destName= textField1.getText() + File.separator + sourceFileName;
            System.out.println("    dest file name=" + destName);
            File dest= new File(destName);
            return dest;
    }

    /**
   *由原文件和下载目录构造目标文件
   * @param fa 文件处理授权
   * @param sourceFileName 原文件名
   * @return 目标文件
   */
    private File getDestFile2(String sourceFileName) {
            String destName= textField1.getText() + File.separator + sourceFileName;
            System.out.println("    dest file name=" + destName);
            File dest= new File(destName);
            return dest;
    }

        /**
     * 检查本地目标文件是否存在;如果存在,是否需要覆盖;
     * @param fa
     * @param dest
     * @return 0,正常容许下载(或覆盖);1,不需要下载(已存在,不需要覆盖);3,发生异常
     */
    private int checkDestFile(FileAccess fa, File dest)
    {
        int result=0;
         if(fa.exists(dest))
        {
            String msg= dest.getName() + "已存在,是否覆盖?";
            int option = throwConfirmMessge(msg);
            if(VERBOSE)
                System.out.println("    confirm result=" + option);
            if(option==0)//需要覆盖,因此先删除
            {
                fa.delete(dest);
                if(fa.exists(dest))
                {
                    if(VERBOSE)
                        System.out.println("    the file " + dest.getName() + "  can't be deleted.");
                    JOptionPane.showMessageDialog(this, "无法覆盖文件: " + dest.getName());
                    result=2;
                }
                else
                {
                   if(VERBOSE)
                        System.out.println("    the file " + dest.getName() + "  has been deleted.");
                   result=0;
                }
            }
            else//不需要覆盖
            {
                result=1;
            }
        }
        if(VERBOSE)
            System.out.println("   checkDestFile---result=" + result);
        return result;
    }

     /**
     * 启动一个消息对话框,让用户进行确认
     * @param msg
     */
    private int  throwConfirmMessge(String msg)
    {
        //Custom button text
        String title="警告";
        Object[] options = {"确定","取消"};
        int n = JOptionPane.showOptionDialog(this, msg,title, JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options,options[0]);
        return n;
    }

    private void copyFile(FileAccess fa, FileInputStream source, File dest) throws IOException
    {
        FileOutputStream fos = fa.getFileOutputStream(dest);
        byte[] buf = new byte[4096];
        int len;
        try {
            while ((len = source.read(buf)) >= 0)
                fos.write(buf, 0, len);
        }
        finally {
            fos.close();
            source.close();
        }
        System.out.println("    copy done");
    }
     public void start()
     {
        WTContext.getContext(this).start();
        if(VERBOSE)
            System.out.println("start wtcontext.");
        super.start();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private java.awt.Label label1;
    private java.awt.TextArea textArea1;
    private java.awt.TextField textField1;
    // End of variables declaration//GEN-END:variables

}
